<template>
  <div>
    <n-button quaternary type="info" @click="clear(), (forgetModal = true)">忘记密码？</n-button>
    <n-modal v-model:show="forgetModal" :mask-closable="false" preset="dialog" title="重置登录密码">
      <n-form :model="modelRef" ref="formRef" :rules="rules">
        <n-form-item path="email" label="邮箱地址">
          <n-input
            v-model:value="modelRef.email"
            @keydown.enter.prevent
            :show-button="false"
            style="width: 100%"
            maxlength="100"
          />
        </n-form-item>
        <n-form-item path="loginName" label="登录名" style="margin-top: 15px">
          <n-input
            v-model:value="modelRef.loginName"
            @input="handlePasswordInput"
            type="text"
            @keydown.enter.prevent
            style="width: 100%"
            maxlength="30"
          />
        </n-form-item>
        <n-space justify="right">
          <n-form-item>
            <n-space>
              <n-button @click="forgetModal = false" size="medium"> 取消 </n-button>
              <n-button @click="resetConfirm" attr-type="button" size="medium" type="info"
                >确认</n-button
              >
            </n-space>
          </n-form-item>
        </n-space>
      </n-form>
    </n-modal>
  </div>
</template>

<script lang='ts' setup>
import { resetPassword } from '@/api/merchantPassword/resetPassword';
import { ref } from 'vue';
import { useMessage } from 'naive-ui';
import { createStorage } from '@/utils/Storage';

const forgetModal = ref(false); // 是否显示模态框

const formRef = ref(null);

const message = useMessage();

const modelRef = ref({
  email: null,
  loginName: null,
});

// 表单验证规则
const rules = {
  loginName: {
    required: true,
    trigger: 'blur',
    message: '请输入登录名',
  },
  email: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入邮箱');
      } else if (!/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(value)) {
        return new Error('请输入正确的邮箱格式');
      } else {
        return true;
      }
    },
    trigger: 'blur',
  },
};

const resetConfirm = async (e) => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      await resetPassword(modelRef.value).then((res) => {
        console.log(res);
        if (res.data.sysHead.retCd == '000000') {
          console.log(res);
          message.success('重置密码成功');
          clear();
        }
      });
      forgetModal.value = false;
    } else {
      message.error('重置密码失败');
    }
  });
};

const clear = () => {
  modelRef.value.email = null;
  modelRef.value.loginName = null;
};
</script>